package com.wuchengdong.web.extend.auth;

import com.wuchengdong.web.pojo.User;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import static com.baomidou.mybatisplus.extension.parser.JsqlParserGlobal.executorService;
import static com.wuchengdong.web.extend.utils.ValidateCodeOrTokenUtils.generateToken;

/**
 * 策略：本地map维护token数据 一旦程序重启 map也会消失
 */
@Component
public class LocalMapAuthHandler implements AuthHandler {

    private final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();

    private Map<String, Integer> tokenMap = new HashMap<>();

    @Override
    public String saveNewTokenWithUser(User user) {
        String token = generateToken(32);
        tokenMap.put(token, user.getId());
        executorService.schedule(() -> { //30天后自动删除 有全局异常处理 不怕报错
            tokenMap.remove(token);
        }, 30, TimeUnit.DAYS);
        return token;
    }

    @Override
    public void cleanTokenWithUser(String token, int id) {
        tokenMap.remove(token);
        if (tokenMap.containsValue(id)) {
            tokenMap.forEach((k, v) -> {
                if (Objects.equals(v, id)) {
                    tokenMap.remove(k);
                }
            });
        }
    }

    @Override
    public int getUserByToken(String token) {
        return tokenMap.get(token);
    }

    @Override
    public boolean checkToken(String token,User user) {
        return Objects.equals(tokenMap.get(token), user.getId());
    }
}
